import React, { Fragment } from "react";
import CartItem from "./CartItem";
import response from "../response.json";
import { connect } from "react-redux";
import { saveToCartCreator } from "../store/creators/cart.creator";

class Cart extends React.Component {
  // 组件挂载完成之后
  componentDidMount() {
    // 保存购物车列表
    this.props.saveToCart();
  }

  render() {
    return (
      <div className="card mb-4">
        <div className="card-header py-3">
          <h5 className="mb-0">购物车 - 共 2 件商品</h5>
        </div>
        <div className="card-body">
          {this.props.cart.map((item, index) => {
            if (index < this.props.cart.length - 1) {
              return (
                <Fragment key={item.id}>
                  <CartItem {...item} />
                  <hr className="my-4" />
                </Fragment>
              );
            }
            return <CartItem key={item.id} {...item} />;
          })}
        </div>
      </div>
    );
  }
}

// 通过从 store 中获取购物车列表来验证购物车列表是否存储成功
const mapStateToProps = (state) => ({ cart: state.cartReducer.cart });

const mapDispatchToProps = (dispatch) => ({
  saveToCart() {
    // 保存购物车列表
    dispatch(saveToCartCreator(response));
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(Cart);
